package com.dc.free.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.dc.free.util.WebUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;

public class WeiXinAuthInterceptor implements Interceptor {

	private String state;
	private String code;
	
	public static final String STATE = PropKit.get("weixin.state");
	
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		ApiConfig apiConfig = WeiXInConfigIntercept.apiConfig;
		ApiConfigKit.setThreadLocalApiConfig(apiConfig);
		
		HttpServletRequest request = controller.getRequest();
		Object openid = request.getSession().getAttribute("openid");
		state = controller.getPara("state");
		
		if(openid==null && !STATE.equals(state)) {
			String redirectUrl = WebUtil.getUrlWithParameter(request);
			request.getSession().setAttribute("redirectUrl", redirectUrl);
			controller.redirect(SnsAccessTokenApi.getAuthorizeURL(apiConfig.getAppId(), redirectUrl, STATE, true));
			//controller.redirect(WeiXinService.getOAuth2CodeUrl(IHttpKit.encode(redirectUrl, "utf-8"), WeiXinService.OAUTH2_SNSAPIBASE));
			return;
		}
		
		if(openid==null && STATE.equals(state)) {
			code = controller.getPara("code");
			SnsAccessToken  snsAccessToken =SnsAccessTokenApi.getSnsAccessToken(apiConfig.getAppId(), apiConfig.getAppSecret(), code);
			openid = snsAccessToken.getOpenid();
			request.getSession().setAttribute("openid", openid);
			
			String redirectUrl = request.getSession().getAttribute("redirectUrl").toString();
			controller.redirect(redirectUrl);
			return;
		}
		
		inv.invoke();
	}
	
	
}